package me.sdevil507.platform.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import me.sdevil507.biz.common.sysdict.po.QSysDict;
import me.sdevil507.biz.common.sysdict.po.SysDict;
import me.sdevil507.biz.common.sysdict.repository.SysDictRepository;
import me.sdevil507.biz.fruit.dto.FruitParamsDTO;
import me.sdevil507.biz.fruit.dto.FruitWxAppletDTO;
import me.sdevil507.biz.fruit.dto.FruitWxAppletParamsDTO;
import me.sdevil507.biz.fruit.mapper.FruitMapper;
import me.sdevil507.biz.fruit.po.*;
import me.sdevil507.biz.fruit.repository.*;
import me.sdevil507.biz.fruit.service.FruitOrgRelService;
import me.sdevil507.biz.fruit.service.FruitService;
import me.sdevil507.biz.fruit.service.FruitWxAppletExService;
import me.sdevil507.biz.fruit.service.FruitWxAppletService;
import me.sdevil507.mobile.wxApplet.util.WxUtil;
import me.sdevil507.org.po.*;
import me.sdevil507.org.repository.OrgExpertInfoRepository;
import me.sdevil507.org.repository.OrgUserRelRepository;
import me.sdevil507.org.repository.OrgUserRepository;
import me.sdevil507.org.repository.TempExpertRepository;
import me.sdevil507.org.service.OrgExpertService;
import me.sdevil507.org.service.OrgService;
import me.sdevil507.platform.dto.PlatUtilParamsDto;
import me.sdevil507.platform.po.talent_data_transfer.fruit.NdFruit;
import me.sdevil507.platform.po.talent_data_transfer.fruit.QNdFruit;
import me.sdevil507.platform.po.talent_data_transfer.sysdict.NdSysDict;
import me.sdevil507.platform.po.talent_data_transfer.sysdict.QNdSysDict;
import me.sdevil507.platform.po.talent_data_transfer.talent.NdTalentBasic;
import me.sdevil507.platform.po.talent_data_transfer.talent.QNdTalentBasic;
import me.sdevil507.platform.service.PlatUtilService;
import me.sdevil507.supports.helper.Md5PasswordHelper;
import me.sdevil507.supports.result.ApiResultDTO;
import me.sdevil507.supports.result.ApiResultGenerator;
import me.sdevil507.supports.status.ApiStatusCode;
import me.sdevil507.supports.status.ComConstant;
import me.sdevil507.supports.util.AESUtil;
import me.sdevil507.supports.util.ChatGptUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author hp
 * @Date 2021/5/17 16:37
 * @Description 平台端 工具类
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/plat/util")
@Slf4j
public class PlatUtilController {

    @Autowired
    PlatUtilService platUtilService;

    @Autowired
    JPAQueryFactory jpaQueryFactory;

    @Autowired
    FruitRepository fruitRepository;

    @Autowired
    FruitOrgRelService fruitOrgRelService;

    @Autowired
    FruitOrgRelRepository fruitOrgRelRepository;

    @Autowired
    FruitAuthorRepository fruitAuthorRepository;

    @Autowired
    FruitAuthorOrgRepository fruitAuthorOrgRepository;

    @Autowired
    TempExpertRepository tempExpertRepository;

    @Autowired
    private OrgUserRelRepository orgUserRelRepository;

    @Autowired
    private OrgUserRepository orgUserRepository;

    @Autowired
    private OrgExpertInfoRepository orgExpertInfoRepository;

    @Autowired
    private SysDictRepository sysDictRepository;

    @Autowired
    private FruitFieldRepository fruitFieldRepository;

    @Autowired
    OrgService orgService;

    @Autowired
    OrgExpertService orgExpertService;

    @Autowired
    FruitService fruitService;

    @Autowired
    FruitMapper fruitMapper;

    @Autowired
    private Md5PasswordHelper md5PasswordHelper;

    @Autowired
    FruitWxAppletService fruitWxAppletService;

    @Autowired
    FruitWxAppletExService fruitWxAppletExService;

    @Autowired
    ChatGptUtil chatGptUtil;

    /**
     * 处理临时专家数据
     * @return
     */
    @Transactional
    @RequestMapping(value = "/dealExpertBiz", method = RequestMethod.POST)
    public ApiResultDTO dealExpertBiz() {

        try {
            QFruitAuthorPO qFruitAuthorPO = QFruitAuthorPO.fruitAuthorPO;
            QTempExpertPo qTempExpertPo = QTempExpertPo.tempExpertPo;
            //查询所有作者
            List<Long> authorIdList = jpaQueryFactory.select(qFruitAuthorPO.orgUserId).from(qFruitAuthorPO).where(qFruitAuthorPO.orgUserId.isNotNull()).fetch();
            //不在作者当中的临时专家id ---无成果
            List<Long> tempExpIdList = jpaQueryFactory.select(qTempExpertPo.id).from(qTempExpertPo)
                    .from(qTempExpertPo).where(qTempExpertPo.deleted.isFalse().and(qTempExpertPo.id.notIn(authorIdList))).fetch();
            //执行删除
            tempExpIdList.forEach(tempId->{
                tempExpertRepository.logicDelete(tempId);
            });

            List<OrgPo> orgList = orgService.readAll();
            if(!CollectionUtils.isEmpty(orgList)){
                for (int i = 1; i <= orgList.size(); i++) {
                    Long orgId = orgList.get(i-1).getId();
                    /**
                     * 1 查询临时专家库中重复的专家名的数据--取一个
                     * 2 查询出对应的成果作者中的专家id，
                     * 3 更新成临时专家里面的专家id，
                     * 4 之后删除被合并的临时专家
                     */
                    log.info("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
                    log.info("|||********************第 " + i + " 家智库********************   "+orgList.get(i-1).getNameZh()+"********************开始执行********************|||");
                    log.info("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||");
                    log.info("-----------------------------------1 开始执行合并重复临时专家---------------------------------------------");
                    List<String> realNameList = jpaQueryFactory.select(qTempExpertPo.realName).from(qTempExpertPo)
                            .where(qTempExpertPo.deleted.isFalse().and(qTempExpertPo.orgID.eq(orgId)))
                            .groupBy(qTempExpertPo.realName).having(qTempExpertPo.realName.count().gt(1)).fetch();
                    realNameList.forEach(name -> {
                        List<TempExpertPo> tempExpertPos = jpaQueryFactory.select(qTempExpertPo).from(qTempExpertPo)
                                .where(qTempExpertPo.deleted.isFalse().and(qTempExpertPo.realName.eq(name))).fetch();
                        // 1
                        long firstExpertId = tempExpertPos.get(0).getId();
                        tempExpertPos.forEach(tempExpertPo -> {
                            // 2
                            FruitAuthorPO fap = fruitAuthorRepository.findById(tempExpertPo.getId()).orElse(null);
                            if(fap != null){
                                // 3
                                log.info("-------------------------1-1---------开始执行合并重复临时专家---"+firstExpertId+"-----合并成果作者id为重复中的第一个临时专家----"+fap.getOrgUserId()+"---" + qFruitAuthorPO.author);
                                fruitAuthorRepository.temporaryBecomeFormal(fap.getOrgUserId(), firstExpertId);
                            }
                            // 4
                            if(!tempExpertPo.getId().equals(firstExpertId)){
                                tempExpertRepository.logicDelete(tempExpertPo.getId());
                                log.info("-------------------------1-2---------开始执行合并重复临时专家--------删除重复临时专家(除了第一个)-------------" + tempExpertPo.getRealName());
                            }
                        });
                    });

                    /**
                     * 1 查询临时专家库中和专家库中名字一样的专家，
                     * 2 查询出对应的成果作者中的专家id，
                     * 3 更新成专家库里面的专家id，
                     * 4 之后删除临时专家
                     */
                    log.info("-----------------------------------2 开始执行 查询专家库中和临时专家库中名字一样的专家---------------");
                    QOrgUserPo qOrgUserPo = QOrgUserPo.orgUserPo;
                    QOrgUserRelPo qOrgUserRelPo = QOrgUserRelPo.orgUserRelPo;
                    Map<Long, Long> map = new HashMap<>();
                    // 1 取相同机构下  相同名字的专家
                    jpaQueryFactory.select(qOrgUserPo.id, qTempExpertPo.id).from(qOrgUserRelPo)
                            .leftJoin(qOrgUserPo).on(qOrgUserRelPo.user.id.eq(qOrgUserPo.id))
                            .leftJoin(qTempExpertPo).on(qOrgUserPo.realName.eq(qTempExpertPo.realName))
                            .where(qOrgUserRelPo.org.id.eq(orgId).and(qTempExpertPo.orgID.eq(orgId))
                                    .and(qOrgUserPo.deleted.isFalse())
                                    .and(qTempExpertPo.deleted.isFalse())
                            )
                            .fetch().forEach(tuple -> {
                        map.put(tuple.get(qTempExpertPo.id), tuple.get(qOrgUserPo.id));
                    });
                    map.forEach((key, value) -> {
                        long tempExpId = key;
                        // 2 查询临时专家对应的成果作者
                        jpaQueryFactory.selectFrom(qFruitAuthorPO)
                                .where(qFruitAuthorPO.orgUserId.eq(tempExpId).and(qFruitAuthorPO.isDel.isFalse()))
                                .fetch()
                                .forEach(qf -> {
                                    log.info("-------------------------2-1---------开始执行 查询专家库中和临时专家库中名字一样的专家-" + value + "---- 更新临时专家对应的成果作者--" + qf.getOrgUserId() + "--为专家库里面的专家id-------" + value);
                                    //查询是否当前专家有专家角色
                                    Predicate predicate = qOrgUserRelPo.id.isNotNull().and(qOrgUserRelPo.org.id.eq(orgId)).and(qOrgUserRelPo.user.id.eq(value));
                                    OrgUserRelPo orgUserRelPo = orgUserRelRepository.findOne(predicate).orElse(null);
                                    if(orgUserRelPo != null && !orgUserRelPo.isExpert()){
                                        //没有专家角色 更新成专家
                                        orgUserRelPo.setExpert(true);
                                        orgUserRelRepository.save(orgUserRelPo);
                                    }
                                    //批量更新
                                    fruitAuthorRepository.temporaryBecomeFormal(qf.getOrgUserId(), value);
                                });
                        // 4 删除临时专家
                        log.info("-------------------------2-2---------开始执行 查询专家库中和专家库中名字一样的专家-----逻辑删除临时专家---------------");
                        tempExpertRepository.logicDelete(tempExpId);
                    });


                    /**
                     * 1 取相同机构下  查询成果作者中的专家
                     * 2 取相同机构下  查询专家库中的专家
                     * 3 比较相同后更新成专家库里面的专家id
                     */
                    log.info("-----------------------------------3 开始执行 查询 成果作者中 和专家库中名字一样的专家---------------");
                    // 1 取相同机构下  查询成果作者中的专家
                    QFruitOrgRelPo qFruitOrgRelPo = QFruitOrgRelPo.fruitOrgRelPo;
                    List<FruitAuthorPO> fruitAuthorPOList = jpaQueryFactory.select(qFruitAuthorPO).from(qFruitOrgRelPo)
                            .leftJoin(qFruitAuthorPO).on(qFruitAuthorPO.fruitId.eq(qFruitOrgRelPo.fruitId))
                            .where(qFruitOrgRelPo.orgId.eq(orgId).and(qFruitAuthorPO.isDel.isFalse()))
                            .fetch();
                    // 2 取相同机构下  查询专家库中的专家
                    List<OrgUserPo> orgUserPoList = jpaQueryFactory.select(qOrgUserPo).from(qOrgUserRelPo)
                            .leftJoin(qOrgUserPo).on(qOrgUserRelPo.user.id.eq(qOrgUserPo.id))
                            .where(qOrgUserRelPo.org.id.eq(orgId).and(qOrgUserPo.deleted.isFalse()))
                            .fetch();
                    orgUserPoList.forEach(orgUserPo -> {
                        for (FruitAuthorPO fruitAuthorPO : fruitAuthorPOList) {
                            //如果名字相同但是id不同
                            if(orgUserPo.getRealName().equals(fruitAuthorPO.getAuthor()) && !orgUserPo.getId().equals(fruitAuthorPO.getOrgUserId())){
                                fruitAuthorPO.setOrgUserId(orgUserPo.getId());
                                fruitAuthorRepository.save(fruitAuthorPO);
                                log.info("-------------------------3-1---------开始执行 更新成果作者中---authId=-"+fruitAuthorPO.getId()+"----"+fruitAuthorPO.getAuthor()+"----为专家库---"+orgUserPo.getRealName()+"--------");
                            }
                        }
                    });

                    /**
                     * 1 取相同机构下  查询成果作者中的专家
                     * 2 查询专家的id是否在临时专家（isDel=0），如果不在，是否在正式专家库，如果都不在，更新成临时专家或者正式专家id
                     */
                    log.info("-----------------------------------4 开始执行 查询 查询成果作者中的专家 id不属于临时和正式专家的情况---------------");
                    // 1 取相同机构下  查询成果作者中的专家
                    List<FruitAuthorPO> fruitAuthorList = jpaQueryFactory.select(qFruitAuthorPO).from(qFruitOrgRelPo)
                            .leftJoin(qFruitAuthorPO).on(qFruitAuthorPO.fruitId.eq(qFruitOrgRelPo.fruitId))
                            .where(qFruitOrgRelPo.orgId.eq(orgId).and(qFruitAuthorPO.isDel.isFalse()))
                            .fetch();
                    //机构下的临时专家--未删除的专家
                    Map<String, Long> noDeleteTempExpertMap = jpaQueryFactory.selectFrom(qTempExpertPo).where(
                                qTempExpertPo.deleted.isFalse().and(qTempExpertPo.orgID.eq(orgId))
                            ).fetch().stream().collect(Collectors.toMap(TempExpertPo::getRealName, TempExpertPo::getId));
                    //机构下的临时专家--已删除的专家
                    /*Map<String, Long> deletedTempExpertMap = jpaQueryFactory.selectFrom(qTempExpertPo).where(
                                qTempExpertPo.deleted.isTrue().and(qTempExpertPo.orgID.eq(orgId))
                            ).fetch().stream().collect(Collectors.toMap(TempExpertPo::getRealName, TempExpertPo::getId));*/
                    //机构下的正式专家库表
                    Map<String, Long> orgUserMap = jpaQueryFactory.select(qOrgUserPo).from(qOrgUserRelPo).leftJoin(qOrgUserPo).on(qOrgUserRelPo.user.id.eq(qOrgUserPo.id))
                            .where(qOrgUserRelPo.org.id.eq(orgId)
                                    .and(qOrgUserPo.deleted.isFalse())
                            ).fetch().stream().collect(Collectors.toMap(OrgUserPo::getRealName, OrgUserPo::getId));;
                    //循环比较
                    for (FruitAuthorPO fruitAuthorPO : fruitAuthorList) {
                        //比较临时专家（未删除）
                        Long noDelTempExpertId =  noDeleteTempExpertMap.get(fruitAuthorPO.getAuthor());
                        if(noDelTempExpertId != null && !noDelTempExpertId.equals(fruitAuthorPO.getOrgUserId())){
                            log.info("-------------------------4-1---------更新-成果中的专家---authId=-"+fruitAuthorPO.getId()+"----"+fruitAuthorPO.getAuthor()+"---"+fruitAuthorPO.getOrgUserId()+"---为临时库未删除的专家--"+noDelTempExpertId+"-------");
                            fruitAuthorPO.setOrgUserId(noDelTempExpertId);
                            fruitAuthorRepository.save(fruitAuthorPO);
                            break;
                        }
                        //比较正式库专家
                        Long orgUserId =  orgUserMap.get(fruitAuthorPO.getAuthor());
                        if(orgUserId != null && !orgUserId.equals(fruitAuthorPO.getOrgUserId())){
                            log.info("-------------------------4-2---------更新-成果中的专家---authId=-"+fruitAuthorPO.getId()+"----"+fruitAuthorPO.getAuthor()+"---"+fruitAuthorPO.getOrgUserId()+"---为正式库的专家--"+orgUserId+"-------");
                            fruitAuthorPO.setOrgUserId(orgUserId);
                            fruitAuthorRepository.save(fruitAuthorPO);
                            break;
                        }
                        /*//比较临时专家（已删除）
                        Long deletedTempExpertId =  deletedTempExpertMap.get(fruitAuthorPO.getAuthor());
                        if(deletedTempExpertId != null && deletedTempExpertId.equals(fruitAuthorPO.getOrgUserId())){
                            log.info("-------------------------4----------更新-成果中的专家---authId=-"+fruitAuthorPO.getId()+"----"+fruitAuthorPO.getAuthor()+"---"+fruitAuthorPO.getOrgUserId()+"---为临时库已删除的专家--"+deletedTempExpertId+"-------");
                            fruitAuthorPO.setOrgUserId(deletedTempExpertId);
                            fruitAuthorRepository.save(fruitAuthorPO);

                            //把已删除的专家更新成未删除
                            TempExpertPo tempExpertPo = tempExpertRepository.getOne(deletedTempExpertId);
                            tempExpertPo.setDeleted(false);
                            tempExpertRepository.save(tempExpertPo);
                            break;
                        }*/
                    }
                    log.info("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||**");
                    log.info("|||********************第 " + i + " 家智库********************   "+orgList.get(i-1).getNameZh()+"   ********************执行结束********************||||");
                    log.info("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||**");
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            return ApiResultGenerator.create(ApiStatusCode.ERROR.getCode(), ApiStatusCode.ERROR.getDescription());
        }
        return ApiResultGenerator.create(ApiStatusCode.SUCCESS.getCode(), ApiStatusCode.SUCCESS.getDescription());
    }



    /**
     *
     原来的媒体成果  小类型改成10
     接受采访： 大类型type值改成5  小类型改成11
     接待来访： 新增大类型type值为4 小类型为2

     为所有专家添加成果对应关系并设置状态为1
     fruit表中的initFruitId更新为fruitId
     fruitOrgRel表中的initFruitId更新为fruitId

     删除fruit表is_adopt/ journal_type_name /adopt_deparment/adopt_time
     删除biz_fruit_org_rel的fruitid索引
     删除biz_fruit的init_fruitid索引

     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/dealTipsBiz", method = RequestMethod.POST)
    public ApiResultDTO dealTipsBiz() {
        try {
            QFruitPO qFruitPO = QFruitPO.fruitPO;
            QFruitOrgRelPo qFruitOrgRelPo = QFruitOrgRelPo.fruitOrgRelPo;
            List<FruitOrgRelPo> fruitOrgRelPos = jpaQueryFactory.selectFrom(qFruitOrgRelPo).fetch();
            List<Long> fruitIds = new ArrayList<>();
            // fruitOrgRel表中的initFruitId更新为fruitId
            if(!CollectionUtils.isEmpty(fruitOrgRelPos)){
                for (int i=0;i<fruitOrgRelPos.size();i++){
                    FruitOrgRelPo fruitOrgRelPo = fruitOrgRelPos.get(i);
                    log.info("------"+ i +"------把fruitOrgRel表中的initFruitId更新为fruitId------------" + fruitOrgRelPo.getFruitId());
                    fruitOrgRelPo.setInitFruitId(fruitOrgRelPo.getFruitId());
                    fruitOrgRelRepository.save(fruitOrgRelPo);

                    fruitIds.add(fruitOrgRelPo.getFruitId());
                };
            }
            // 原来的媒体成果 小类型改成10
            List<FruitPO> fruitPOS = jpaQueryFactory.selectFrom(qFruitPO).where(qFruitPO.isDel.isFalse().and(qFruitPO.id.in(fruitIds))).fetch();
            if(!CollectionUtils.isEmpty(fruitPOS)){
                for (int m=0;m<fruitPOS.size();m++){
                    FruitPO fruitPO = fruitPOS.get(m);
                    log.info("------处理第----"+ (m+1) +"个-------成果 ------------" + fruitPO.getName());
                    if(ComConstant.FruitType.NewspaperORNetwork.equals(fruitPO.getType())){
                        fruitPO.setActivityProdType(ComConstant.FruitType.MEDIA_PUBLISHED_ARTICLES);
                        log.info("----------------更新原来的媒体成果 小类型改成10------------" + fruitPO.getName());
                    }else if(ComConstant.FruitType.PolicyAdvice.equals(fruitPO.getType()) && ComConstant.FruitType.RECEIVE_VISITORS.equals(fruitPO.getActivityProdType())){
                        fruitPO.setType(ComConstant.FruitType.NewspaperORNetwork);
                        fruitPO.setActivityProdType(ComConstant.FruitType.MEDIA_INTERVIEW);
                        log.info("-----------------更新接受采访： 大类型type值改成5  小类型改成11------------" + fruitPO.getName());
                    }
                    fruitPO.setInitFruitId(fruitPO.getId());
                    fruitRepository.save(fruitPO);

//                    List<FruitAuthorPO> fruitAuthorPOS = fruitPO.getAuthorPOList();
//                    if(!CollectionUtils.isEmpty(fruitAuthorPOS)){
//                        for (int n=0;n<fruitAuthorPOS.size();n++){
//                            FruitAuthorPO authorPO = fruitAuthorPOS.get(n);
//                            if(authorPO.getOrgUserId() != null){
//                                FruitOrgRelPo fruitOrgRelPo = jpaQueryFactory.selectFrom(qFruitOrgRelPo).where(qFruitOrgRelPo.fruitId.eq(fruitPO.getId()).and(qFruitOrgRelPo.authUserId.eq(authorPO.getOrgUserId()))).fetchOne();
//                                if(fruitOrgRelPo == null){
//                                    fruitOrgRelPo = new FruitOrgRelPo();
//                                    fruitOrgRelPo.setFruitId(fruitPO.getId());
//                                    fruitOrgRelPo.setInitFruitId(fruitPO.getId());
//                                    fruitOrgRelPo.setAuthUserId(authorPO.getOrgUserId());
//                                    fruitOrgRelPo.setStatus("1");
//                                    log.info("-----为成果--"+fruitPO.getName()+"---第---"+ n +"---个专家添加成果对应关系并设置状态为1------------" + authorPO.getAuthor());
//                                    fruitOrgRelRepository.save(fruitOrgRelPo);
//                                }else{
//                                    log.info("======为成果--"+fruitPO.getName()+"---第---"+ n +"---为专家添加成果对应关系并设置状态为1=========" + authorPO.getAuthor() + "-----已存在----fruitId====-" + fruitPO.getId());
//                                }
//                            }
//                        };
//                    }

                };
            }
            QFruitAuthorPO qFruitAuthorPO = QFruitAuthorPO.fruitAuthorPO;
            List<FruitAuthorPO> fruitAuthorPOS = jpaQueryFactory.selectFrom(qFruitAuthorPO).where(qFruitAuthorPO.isDel.isFalse().and(qFruitAuthorPO.fruitId.in(fruitIds))).fetch();
            if(!CollectionUtils.isEmpty(fruitAuthorPOS)){
                for (int n=0;n<fruitAuthorPOS.size();n++){
                    FruitAuthorPO authorPO = fruitAuthorPOS.get(n);
                    FruitOrgRelPo fruitOrgRelPo = new FruitOrgRelPo();
                    fruitOrgRelPo.setFruitId(authorPO.getFruitId());
                    fruitOrgRelPo.setInitFruitId(authorPO.getFruitId());
                    fruitOrgRelPo.setAuthUserId(authorPO.getOrgUserId());
                    fruitOrgRelPo.setStatus("1");
                    log.info("---共"+fruitAuthorPOS.size()+"个---运行到第---"+ n +"---个成果id=--"+authorPO.getFruitId()+"--专家添加成果对应关系并设置状态为1------------" + authorPO.getAuthor());
                    fruitOrgRelRepository.save(fruitOrgRelPo);
                }
            }
            log.info("------------全部结束----------------");
            log.info("------------全部结束----------------");
            log.info("------------全部结束----------------");


        } catch (Exception e) {
            e.printStackTrace();
        }
        return ApiResultGenerator.create(ApiStatusCode.SUCCESS.getCode(), ApiStatusCode.SUCCESS.getDescription());
    }

    @RequestMapping(value = "/dealDeptUser", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ApiResultDTO dealDeptUser() {
        try {
            platUtilService.dealDeptUser();

        } catch (Exception e) {
            log.error("导入成果数据失败:", e);
            return ApiResultGenerator.create("-1", "导入成果数据失败!");
        }
        return ApiResultGenerator.create(ApiStatusCode.SUCCESS.getCode(), ApiStatusCode.SUCCESS.getDescription());
    }


    @RequestMapping(value = "/importOrgManager", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ApiResultDTO importOrgManager(@RequestParam("file") MultipartFile file) {
        try {
            // 获取文件原始名称
            String originalFileName = file.getOriginalFilename();
            // 创建临时文件
            assert originalFileName != null;
            File tempFile = File.createTempFile("temp", originalFileName.substring(originalFileName.lastIndexOf(".")));
            // 将上传文件转为临时文件
            file.transferTo(tempFile);
            // 退出时删除临时文件
            tempFile.deleteOnExit();
            // 执行导入
            return platUtilService.importOrgManager(tempFile);
        } catch (IOException e) {
            log.error("导入成果数据失败:", e);
            return ApiResultGenerator.create("-1", "导入机构人员数据失败!");
        }
    }

    @RequestMapping(value = "/dealOrgExpert", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ApiResultDTO dealOrgExpert(@RequestParam("file") MultipartFile file) {
        try {
            // 获取文件原始名称
            String originalFileName = file.getOriginalFilename();
            // 创建临时文件
            assert originalFileName != null;
            File tempFile = File.createTempFile("temp", originalFileName.substring(originalFileName.lastIndexOf(".")));
            // 将上传文件转为临时文件
            file.transferTo(tempFile);
            // 退出时删除临时文件
            tempFile.deleteOnExit();
            // 执行导入
            return platUtilService.dealOrgExpert(tempFile);
        } catch (IOException e) {
            log.error("导入成果数据失败:", e);
            return ApiResultGenerator.create("-1", "导入机构专家数据失败!");
        }
    }

    @RequestMapping(value = "/dealOrgFruit", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ApiResultDTO dealOrgFruit(@RequestParam("file") MultipartFile file) {
        try {
            // 获取文件原始名称
            String originalFileName = file.getOriginalFilename();
            // 创建临时文件
            assert originalFileName != null;
            File tempFile = File.createTempFile("temp", originalFileName.substring(originalFileName.lastIndexOf(".")));
            // 将上传文件转为临时文件
            file.transferTo(tempFile);
            // 退出时删除临时文件
            tempFile.deleteOnExit();
            // 执行导入
            return platUtilService.dealOrgFruit(tempFile);
        } catch (IOException e) {
            log.error("导入成果数据失败:", e);
            return ApiResultGenerator.create("-1", "导入成果数据失败!");
        }
    }

    @RequestMapping(value = "/dealFruitKeyWord", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ApiResultDTO dealFruitKeyWord(@RequestBody FruitParamsDTO fruitParamsDTO) {
        try {
            platUtilService.dealFruitKeyWord(fruitParamsDTO);

        } catch (Exception e) {
            log.error("提取成果关键词失败:", e);
            return ApiResultGenerator.create("-1", "提取成果关键词失败!");
        }
        return ApiResultGenerator.create(ApiStatusCode.SUCCESS.getCode(), ApiStatusCode.SUCCESS.getDescription());
    }

    /**
     * 说明：
     *
     * 先执行下面语句
     *
     把专家库的数据表导入到平台库中，再执行下面的方法

     1 -- 扩展专家信息表字段

     ALTER TABLE biz_org_expert_info ADD COLUMN company_address  varchar(200);
     ALTER TABLE biz_org_expert_info ADD COLUMN graduate_school  varchar(200);
     ALTER TABLE biz_org_expert_info ADD COLUMN join_party_time  varchar(200);
     ALTER TABLE biz_org_expert_info ADD COLUMN link_address  varchar(200);
     ALTER TABLE biz_org_expert_info ADD COLUMN post  varchar(200);
     ALTER TABLE biz_org_expert_info ADD COLUMN work_time  datetime;
     ALTER TABLE biz_org_expert_info ADD COLUMN working_dept  varchar(200);
     ALTER TABLE biz_org_expert_info ADD COLUMN working_station  varchar(200);
     ALTER TABLE biz_org_expert_info ADD COLUMN faculty_sources  varchar(200);
     ALTER TABLE biz_org_expert_info ADD COLUMN cooperation_num  varchar(200);


     2 -- 已有成果添加字段 patent_type:专利类型，fruit_source  1：平台 2：知网
     ALTER TABLE biz_fruit ADD COLUMN patent_type  varchar(20);
     ALTER TABLE biz_fruit ADD COLUMN research_field  varchar(255);
     ALTER TABLE biz_fruit ADD COLUMN research_direction  varchar(255);
     ALTER TABLE biz_fruit ADD COLUMN fruit_source  varchar(2);

     ALTER TABLE nd_fruit ADD COLUMN fruit_source  varchar(2);

     -- 修改字段表值的类型，方便排序
     alter table biz_sysdict modify column d_value int(0);

     3 -- 更新已有成果表字段值
     update biz_fruit bf set bf.fruit_source = 1;
     update nd_fruit bf set bf.fruit_source = 2;

     3 -- 导入成果表、成果作者表、成果机构表数据 合并后的表替换原来的表 （要保证两个表的列名顺序一样）
     CREATE TABLE combined_fruit AS SELECT * FROM biz_fruit UNION ALL SELECT * FROM nd_fruit;

     CREATE TABLE combined_fruit_author AS SELECT * FROM biz_fruit_author UNION ALL SELECT * FROM nd_fruit_author;

     CREATE TABLE combined_fruit_author_org AS SELECT * FROM biz_fruit_author_org UNION ALL SELECT * FROM nd_fruit_author_org;

     -- 添加主键及索引及外键
     ALTER TABLE combined_fruit add primary key(id);

     -- 备份原来的三张表，改名合并的三张表名改为原来的三张表

     ALTER TABLE combined_fruit add primary key(id);
     ALTER TABLE combined_fruit ADD INDEX index_fruit_type (`type`);
     ALTER TABLE combined_fruit ADD INDEX index_fruit_id (`id`);
     ALTER TABLE combined_fruit ADD INDEX index_name (`name`);
     ALTER TABLE combined_fruit ADD INDEX fruit_research_field (`research_field`);
     ALTER TABLE combined_fruit ADD INDEX fruit_field (`field`);


     ALTER TABLE combined_fruit_author add primary key(id);
     ALTER TABLE combined_fruit_author ADD INDEX index_fruit_id (`fruit_id`);
     ALTER TABLE combined_fruit_author ADD INDEX index_name (`author`);
     ALTER TABLE combined_fruit_author ADD INDEX index_org_user_id (`org_user_id`);


     ALTER TABLE combined_fruit_author_org add primary key(id);
     ALTER TABLE combined_fruit_author_org ADD INDEX index_author_id (`author_id`);

     -- 修改表名
     ALTER TABLE biz_fruit RENAME TO biz_fruit_bak;
     ALTER TABLE biz_fruit_author RENAME TO biz_fruit_author_bak;
     ALTER TABLE biz_fruit_author_org RENAME TO biz_fruit_author_org_bak;

     ALTER TABLE combined_fruit RENAME TO biz_fruit;
     ALTER TABLE combined_fruit_author RENAME TO biz_fruit_author;
     ALTER TABLE combined_fruit_author_org RENAME TO biz_fruit_author_org;

     ALTER TABLE nd_fruit_field RENAME TO biz_fruit_field;


     -- 导入字典表
     INSERT INTO `biz_sysdict`(`id`, `d_code`, `d_comment`, `d_name`, `d_value`, `parent_id`, `type_key`, `is_del`, `level`, `ranking`, `create_time`, `update_time`) VALUES (113071605385521293, 'ResearchField', '研究领域', '研究领域', '1', 1, 'System', b'0', NULL, NULL, '2023-09-27 14:20:34.000000', '2023-09-27 14:20:34.000000');


     *
     *
     *
     * @param platUtilParamsDto
     * @return
     */

    @Transactional
    @RequestMapping(value = "/transferTalentDataBase", method = RequestMethod.POST)
    public ApiResultDTO transferTalentDataBase(@RequestBody PlatUtilParamsDto platUtilParamsDto) {
        try {
            int batchSize = 2000;
            //成果
            QNdFruit qNdFruit = QNdFruit.ndFruit;
            List<NdFruit> ndFruits = jpaQueryFactory.selectFrom(qNdFruit).fetch();

            System.out.println("--------开始处理成果与机构对应关系---------");
            //成果与机构对应关系
            List<FruitOrgRelPo> fruitOrgRelPos = new ArrayList<>();
            ndFruits.forEach(fruitPO -> {
//                FruitOrgRelPo fruitOrgRelPo = fruitOrgRelService.findByCondition(fruitPO.getId(), platUtilParamsDto.getOrgId(), ComConstant.FruitStatus.APPROVED);
//                if(fruitOrgRelPo == null){
                FruitOrgRelPo fruitOrgRelPo = new FruitOrgRelPo();
                fruitOrgRelPo.setOrgId(platUtilParamsDto.getOrgId());
                fruitOrgRelPo.setFruitId(fruitPO.getId());
                fruitOrgRelPo.setInitFruitId(fruitPO.getId());
                fruitOrgRelPo.setStatus(ComConstant.FruitStatus.APPROVED);

                fruitOrgRelPos.add(fruitOrgRelPo);
//                }
            });
            int flag = 1;
            for (int i = 0; i < fruitOrgRelPos.size(); i += batchSize) {
                System.out.println("-=====处理fruitOrgRelPos第=====" + flag++ +"====次，一次2000条======一共==" + fruitOrgRelPos.size() + "====条=====");
                int end = Math.min(i + batchSize, fruitOrgRelPos.size());
                List<FruitOrgRelPo> batch = fruitOrgRelPos.subList(i, end);
                fruitOrgRelRepository.saveAll(batch);
            }
            System.out.println("--------处理成果与机构对应关系----结束-----");


            System.out.println("--------开始处理添加专家信息---------");
            //添加专家信息
            QNdTalentBasic qNdTalentBasic = QNdTalentBasic.ndTalentBasic;
            List<NdTalentBasic> ndTalentBasics = jpaQueryFactory.selectFrom(qNdTalentBasic).fetch();
            System.out.println("-----共读取到专家信息----" + ndTalentBasics.size() + "----条---");
            List<OrgUserPo> orgUserPoList = new ArrayList<>();
            ndTalentBasics.forEach(ndTalentBasic -> {
                OrgExpertInfoPo orgExpertInfoPo = new OrgExpertInfoPo();

//                long expertInfoId = SnowflakeIdHelper.get().nextId();

                orgExpertInfoPo.setPhoto(ndTalentBasic.getProfilePhoto() );
                orgExpertInfoPo.setNamePinyin(ndTalentBasic.getNamePinyin() );
                orgExpertInfoPo.setNameEn(ndTalentBasic.getNameEn() );
                orgExpertInfoPo.setUsedName(ndTalentBasic.getUsedName() );
                orgExpertInfoPo.setPenName(ndTalentBasic.getPenName() );
                orgExpertInfoPo.setTheTitle(ndTalentBasic.getTheTitle() );
                orgExpertInfoPo.setTitleLevel(ndTalentBasic.getTitleLevel() );
                orgExpertInfoPo.setWechatNum(ndTalentBasic.getWechatNum() );
                orgExpertInfoPo.setCompany(ndTalentBasic.getCompany() );
                orgExpertInfoPo.setAcademicTitle(ndTalentBasic.getAcademicTitle() );
                orgExpertInfoPo.setGender(ndTalentBasic.getGender() );
                orgExpertInfoPo.setBirthday(ndTalentBasic.getBirthday() );
                orgExpertInfoPo.setPoliticsStatus(ndTalentBasic.getPoliticsStatus() );
                orgExpertInfoPo.setNativePlace(ndTalentBasic.getNativePlace() );
                orgExpertInfoPo.setNation(ndTalentBasic.getNation() );
                orgExpertInfoPo.setNationality(ndTalentBasic.getNationality() );
                orgExpertInfoPo.setQqNum(ndTalentBasic.getQqNum() );
                orgExpertInfoPo.setOfficePhone(ndTalentBasic.getOfficePhone() );
                orgExpertInfoPo.setEducation(ndTalentBasic.getEducation() );
                orgExpertInfoPo.setDegree(ndTalentBasic.getDegree() );
                orgExpertInfoPo.setSubject(ndTalentBasic.getSubject() );
                orgExpertInfoPo.setResearchDomain(ndTalentBasic.getResearchDomain() );
                orgExpertInfoPo.setJoinPartyTime(ndTalentBasic.getJoinPartyTime() );
                orgExpertInfoPo.setLinkAddress(ndTalentBasic.getLinkAddress() );
                orgExpertInfoPo.setPost(ndTalentBasic.getPost() );
                orgExpertInfoPo.setWorkTime(ndTalentBasic.getWorkTime() );
                orgExpertInfoPo.setWorkingDept(ndTalentBasic.getWorkingDept() );
                orgExpertInfoPo.setWorkingStation(ndTalentBasic.getWorkingStation() );
                orgExpertInfoPo.setFacultySources(ndTalentBasic.getFacultySources() );
                orgExpertInfoPo.setCooperationNum(ndTalentBasic.getCooperationNum() );
                orgExpertInfoRepository.save(orgExpertInfoPo);

                OrgUserPo orgUserPo = new OrgUserPo();
                orgUserPo.setId(ndTalentBasic.getId());
                orgUserPo.setPhoneNumber(ndTalentBasic.getPhoneNumber());
                orgUserPo.setPassword(AESUtil.encryptPassword(AESUtil.DEFAULT_PASSWORD));
                orgUserPo.setRealName(ndTalentBasic.getRealName());
                orgUserPo.setMail(ndTalentBasic.getMail());
                orgUserPo.setProfilePhoto(ndTalentBasic.getProfilePhoto());
                orgUserPo.setIdNum(ndTalentBasic.getIdNum());
                orgUserPo.setDeleted(false);
                orgUserPo.setLocked(false);
                orgUserPo.setSummary(ndTalentBasic.getSummary());
                orgUserPo.setExpertInfo(orgExpertInfoPo);

                orgUserPoList.add(orgUserPo);
            });
            System.out.println("-----处理添加专家信息--处理结束-----");

            int flag1 = 1;
            for (int i = 0; i < orgUserPoList.size(); i += batchSize) {
                System.out.println("-=====处理expertInfoPoList第=====" + flag1++ +"====次，一次2000条===一共==" + orgUserPoList.size() + "====条=====");
                int end = Math.min(i + batchSize, orgUserPoList.size());
                List<OrgUserPo> batch = orgUserPoList.subList(i, end);
                orgUserRepository.saveAll(batch);
            }

            System.out.println("--------开始处理处理字典表---------");
            //处理字典表
            QSysDict qSysDict = QSysDict.sysDict;
            List<SysDict> sysDicts = jpaQueryFactory.selectFrom(qSysDict).where(qSysDict.typeKey.eq("ResearchField")).orderBy(qSysDict.dvalue.desc()).fetch();
            int maxDvalue = !CollectionUtils.isEmpty(sysDicts) ? Integer.parseInt(sysDicts.get(0).getDvalue()) : 0;
            System.out.println("-----共读取到成果领域最大值：----" + maxDvalue);
            //处理成果领域对应关系
            QNdSysDict qNdSysDict = QNdSysDict.ndSysDict;
            List<NdSysDict> ndSysDicts = jpaQueryFactory.selectFrom(qNdSysDict).where(qNdSysDict.typeKey.eq("ResearchField")).fetch();

            System.out.println("-----共读取到成果领域----" + ndSysDicts.size() + "----条---");

            List<SysDict> newSysDictList = new ArrayList<>();
            ndSysDicts.forEach(ndSysDict -> {

                int newDvalue = Integer.parseInt(ndSysDict.getDValue()) + maxDvalue;

                SysDict newSysDict = new SysDict();
                newSysDict.setId(ndSysDict.getId());
                newSysDict.setDcode(ndSysDict.getDCode());
                newSysDict.setDname(ndSysDict.getDName());
                newSysDict.setDvalue(newDvalue + "");
                newSysDict.setParentId(ndSysDict.getParentId());
                newSysDict.setLevel(ndSysDict.getLevel());
                newSysDict.setRanking(ndSysDict.getRanking());
                newSysDict.setTypeKey("ResearchField");
                newSysDict.setIsDel(false);
                newSysDictList.add(newSysDict);

                //修改领域值
                QFruitField qFruitField = QFruitField.fruitField;
                List<FruitField> fruitFields = jpaQueryFactory.selectFrom(qFruitField).where(qFruitField.fieldValue.eq(ndSysDict.getDValue())).fetch();
                fruitFields = fruitFields.stream().peek(fruitField -> fruitField.setFieldValue(newDvalue + "")).collect(Collectors.toList());
                fruitFieldRepository.saveAll(fruitFields);

            });
            sysDictRepository.saveAll(newSysDictList);

            System.out.println("-----成果领域--处理结束-----");

        } catch (Exception e) {
            e.printStackTrace();
            return ApiResultGenerator.create("-1", "处理数据失败!");
        }
        return ApiResultGenerator.create(ApiStatusCode.SUCCESS.getCode(), ApiStatusCode.SUCCESS.getDescription());
    }

    /**
     * 获取录入的成果数据
     * @param fruitWxAppletParamsDTO
     * @return
     */
    @PostMapping("/getWaitDealWxAppletFruitOfPage")
    public ApiResultDTO getWxAppletFruitOfPage(@RequestBody FruitWxAppletParamsDTO fruitWxAppletParamsDTO) {
        ApiResultDTO apiResultDto;
        try {
            Page<FruitWxAppletPO> pagePos = fruitWxAppletService.getWxAppletFruitOfPage(fruitWxAppletParamsDTO.getSearchDto(), fruitWxAppletParamsDTO.getPageDto(), fruitWxAppletParamsDTO.getSortDto());

            apiResultDto = ApiResultGenerator.create("0", "分页数据获取成功!", pagePos);
        } catch (Exception e) {
            log.error("分页数据获取失败:", e);
            apiResultDto = ApiResultGenerator.create("-1", "分页数据获取失败!");
        }
        return apiResultDto;
    }

    @RequestMapping(value = "/dealWxAppletFruit", method = RequestMethod.GET)
    @Transactional(rollbackFor = Exception.class)
    public ApiResultDTO dealWxAppletFruit() {
        ApiResultDTO apiResultDTO = null;
        try {
            QFruitWxAppletPO qFruitWxAppletPO = QFruitWxAppletPO.fruitWxAppletPO;
            List<FruitWxAppletPO> fruitWxAppletList = jpaQueryFactory.selectFrom(qFruitWxAppletPO).where(qFruitWxAppletPO.isDeal.isFalse()).fetch();
            if(!CollectionUtils.isEmpty(fruitWxAppletList)){
                fruitWxAppletList.forEach(fwp -> {
                    String content = fwp.getContent();
                    String picUrl = fwp.getPicUrl();
                    String ocrText = "";
                    String prompt = "\"已知提取说明分析以下话语，根据内容并且只输出这个名称，主题，举办日期，出席专家，主办单位，举办地点，类型等，其中类型取后面几种中的一种（研究报告，出席会议， 接受采访，授课培训，考察调研，媒体成果，学术论文， 图书出版，荣誉信息）。" +
                            "一定只返回分析输出后面的json格式字符串，禁止生成markdown.作者可能会有多个，请用逗号进行区分。" +
                            "除了规定的数据，不输出其他任何话语，" +
                            "案例：2023年07月18号我跟张三出席了在南京举办的一个论坛，由省委宣传部、省社科联联合举办，江苏省第十七届哲学社会科学优秀成果奖颁奖仪式暨社科界第十六届学术大会高层论坛，" +
                            "主题是“在高质量发展上继续走在前列，谱写‘强富美高’新江苏现代化建设新篇章”\"," +
                            "只输出JSON格式内容: " +
                            "{" +
                            "\"name\": \"江苏省第十七届哲学社会科学优秀成果奖颁奖仪式暨社科界第十六届学术大会高层论坛\"," +
                            "\"theme\":\"在高质量发展上继续走在前列，谱写‘强富美高’新江苏现代化建设新篇章\"," +
                            "\"pubTime\": \"2023-07-18\"," +
                            "\"author\": \"我,张三\"," +
                            "\"type\": \"出席会议\"" +
                            "\"organization\": \"省委宣传部、省社科联\"," +
                            "\"address\":\"江苏省南京市\"," +
                            "\"summary\": \"\"," +
                            "\"keyword\": \"\"" +
                            "}," +
                            "现分析下面一句话: ";
//                    String prompt = "分析[]中的内容并以json格式精准输出下面字段：名称，主题，日期（格式为年月日），出席专家人员（多人用逗号隔开），主办单位，举办地点，关键词，摘要。";
                    try {
                        String responseBody = "";
                        if(!org.springframework.util.StringUtils.isEmpty(picUrl)){
                            ocrText = WxUtil.recognizePrintedTextOcr(picUrl);

                            System.out.println("微信返回的结果-获取OCR---" + ocrText);
                            System.out.println("---glm的prompt---" + prompt + "["+ocrText + "]");

                            responseBody = chatGptUtil.getGlmResult(prompt + "["+ocrText + "]");
                            System.out.println("-----glm解析OCR返回的result-----"+responseBody);
                        }

                        if(!org.springframework.util.StringUtils.isEmpty(content)){
                            responseBody = chatGptUtil.getGlmResult(prompt + "["+content + "]");
                        }

                        responseBody = responseBody.substring(responseBody.indexOf("{"), responseBody.indexOf("}") + 1).replaceAll("，", ",").replace("\\n", "").replace("\\", "");
                        System.out.println("-----处理后的result-----"+responseBody);

                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode jsonNode = objectMapper.readTree(responseBody);

                        String name = jsonNode.get("name").asText();
                        System.out.println("-----解析出的name-----"+name);

                        String theme = jsonNode.get("theme").asText();
                        String pubTime = jsonNode.get("pubTime").asText();
                        String author = jsonNode.get("author").asText();
                        String organization = jsonNode.get("organization").asText();
                        String address = jsonNode.get("address").asText();
                        String summary = jsonNode.get("summary").asText();
                        String keyword = jsonNode.get("keyword").asText();
                        String typeText = jsonNode.get("type").asText();


                        if(!org.springframework.util.StringUtils.isEmpty(name) || !org.springframework.util.StringUtils.isEmpty(theme) || !org.springframework.util.StringUtils.isEmpty(pubTime) || !org.springframework.util.StringUtils.isEmpty(author) ||
                                !org.springframework.util.StringUtils.isEmpty(organization) || !org.springframework.util.StringUtils.isEmpty(address) || !org.springframework.util.StringUtils.isEmpty(summary) || !org.springframework.util.StringUtils.isEmpty(keyword) ){
                            FruitWxAppletExPO fwxp = new FruitWxAppletExPO();
                            fwxp.setName(name);
                            fwxp.setTheme(theme);
                            fwxp.setPubTime(!org.springframework.util.StringUtils.isEmpty(pubTime) ? pubTime : new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                            fwxp.setAuthor(author.replace("我", fwp.getAddress().replace("本人", fwp.getAddress())));
                            fwxp.setOrganization(organization);
                            fwxp.setAddress(address);
                            fwxp.setSummary(summary);
                            fwxp.setKeyword(keyword);
                            fwxp.setType(
                                    ("研究报告").equals(typeText) ? "3" :
                                            ("出席会议").equals(typeText) ? "4" :
                                                    ("授课培训").equals(typeText) ? "4" :
                                                            ("考察调研").equals(typeText) ? "4" :
                                                                    ("媒体成果").equals(typeText) ? "5" :
                                                                            ("学术论文").equals(typeText) ? "6" :
                                                                                    ("图书出版").equals(typeText) ? "7" :
                                                                                            ("荣誉信息").equals(typeText) ? "8" :
                                                                                                    "4"
                            );
                            fwxp.setWxAppletFruitId(fwp.getId());
                            fwxp.setMobile(fwp.getMobile());
                            fwxp.setOcrText(ocrText);
                            fruitWxAppletExService.save(fwxp);

                            fwp.setIsDeal(true);
                            fruitWxAppletService.save(fwp);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                });
            }

            apiResultDTO = ApiResultGenerator.create(ApiStatusCode.SUCCESS.getCode(), ApiStatusCode.SUCCESS.getDescription());

            System.out.println("===============全部处理完毕=======全部处理完毕======全部处理完毕==============");
        } catch (Exception e) {
            log.error("处理数据失败:", e);
            return ApiResultGenerator.create("-1", "处理数据失败!");
        }
        return apiResultDTO;
    }


    /**
     * 获取转换后的成果数据
     * @param fruitWxAppletParamsDTO
     * @return
     */
    @PostMapping("/getDealtWxAppletFruitOfPage")
    public ApiResultDTO getDealtWxAppletFruitOfPage(@RequestBody FruitWxAppletParamsDTO fruitWxAppletParamsDTO) {
        ApiResultDTO apiResultDto;
        try {

            Page<FruitWxAppletDTO> pagePos = fruitWxAppletExService.getWxAppletFruitOfPage(fruitWxAppletParamsDTO.getSearchDto(), fruitWxAppletParamsDTO.getPageDto(), fruitWxAppletParamsDTO.getSortDto());

            apiResultDto = ApiResultGenerator.create("0", "分页数据获取成功!", pagePos);
        } catch (Exception e) {
            log.error("分页数据获取失败:", e);
            apiResultDto = ApiResultGenerator.create("-1", "分页数据获取失败!");
        }
        return apiResultDto;
    }

    /**
     * 更新数据
     * @param fruitWxAppletExPO
     * @return
     */
    @PostMapping("/updateWxAppletData")
    public ApiResultDTO updateWxAppletData(@RequestBody FruitWxAppletExPO fruitWxAppletExPO) {
        ApiResultDTO apiResultDto;
        try {
            fruitWxAppletExService.save(fruitWxAppletExPO);

            apiResultDto = ApiResultGenerator.create("0", "更新数据成功!");
        } catch (Exception e) {
            log.error("分页数据获取失败:", e);
            apiResultDto = ApiResultGenerator.create("-1", "新数据失败!");
        }
        return apiResultDto;
    }
}
